#ifndef __FILE_H__
#define __FILE_H__

#include "TcpConnection.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sstream>
using std::stringstream;
#include <iostream>
using std::cout; using std::endl;

const string SEND="sendfile/send";
const string RECV="recvfile/recv";

void sendFile(shared_ptr<TcpConnection> pconn)
{
    int fd = ::open(SEND.c_str(), O_RDONLY);
    int readSize = 1;
    int ret = 0;
    string s;
    s.resize(readSize);
    while (1)
    {
        ret = read(fd, &s[0], readSize);
        if (ret <= 0)
        {
            break;
        }
        string tmp(&s[0], ret);
        pconn->sendTcpData(tmp);
//        cout << tmp << endl;
        if (readSize < 20000)
        {
            readSize *= 3;
            s.resize(readSize);
        }
    }
    close(fd);
}

void recvFile(shared_ptr<TcpConnection> pconn)
{
    int port = Socket::getLocalAddr(pconn->sockfd_.fd()).port();
    std::stringstream oss;
    oss << port;
    string s = RECV + oss.str();
    int fd = open(s.c_str(), O_CREAT|O_WRONLY|O_APPEND, 0666);
    queue<string> &que = pconn->getReadQueue();
    while (!que.empty())
    {
        string s = que.front();
 //       cout << s << endl;
        write(fd, &s[0], s.size());
        que.pop();
    }
    ::close(fd);
}

#endif
